<?php
declare (strict_types = 1);

namespace app\api\controller\v1;

use app\api\helpers\v1\traits\FileUpload;
use app\api\helpers\v1\traits\SearchDataForModel;
use app\api\model\v1\AdminLog;
use app\api\model\v1\Attribute;
use app\api\model\v1\CommunityProjectPivot;
use app\api\model\v1\Project;
use app\api\model\v1\ProjectSample;
use app\api\model\v1\ProjectTarget;
use app\BaseController;
use think\Request;

class ProjectCon extends BaseController
{

    use SearchDataForModel,FileUpload;

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2021/12/29 9:33
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 数据源
     */
    public function getProjectList(){
        $limit = $this->request->param('limit',10);
        $type = $this->request->param('type','page');
        if ($type === 'no_page'){
            $res = Project::with(['target'])->select();
        }else{
            $res = $this->search(new Project(),[],$limit,'asc',['target']);
        }
        return $this->response($res);
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2021/12/30 14:42
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 微信端项目列表--数据源
     */
    public function getProjectWxList(){
        $community_id = $this->request->param('community_id');
        $map = [];
        if (!$this->auth->isSuperAdmin($this->request->wx_id)){
            $map[] = array('community_id','=',$community_id);
        }
        $res = CommunityProjectPivot::with(['project'=>['target'=>function($query){
            $query->field('id,target_title,project_id');
            return $query;
        }]])->where($map)->select();
        $new_arr =[];
        foreach ($res as $key=>$v){
            $new_arr[$key]['id'] = $v['project']['id'];
            $new_arr[$key]['label'] = $v['project']['project_title'];
            $new_arr[$key]['target'] = $v['project']['target'];
        }
        return $this->response(array($new_arr));
//        $res = Project::field('id,project_title as label')->with(['target'])->select();

    }


    public function getProjectSelectList(){

        $single = $this->request->param('single',0);

        $community_id = $this->request->param('community_id');
        $res = CommunityProjectPivot::with(['project'=>function($query)use($single){
            if (intval($single) === 1){
                $query->with(['target'])->where(['single'=>0]);
            }else if (intval($single) === 2){
                $query->with(['target'])->where(['single'=>1]);
            }else{
                $query->with(['target']);
            }
            return $query;
        }])->where(['community_id'=>$community_id])->select()->filter(function (CommunityProjectPivot $communityProjectPivot){
            if (!is_null($communityProjectPivot->project)){
                return true;
            }
        });
        $new_arr =[];
        foreach ($res as $key=>$v){
            $new_arr[$key]['value'] = $v['project']['id'];
            $new_arr[$key]['label'] = $v['project']['project_title'];
        }
        return $this->response($new_arr);
//        $res = Project::field('id,project_title as label')->with(['target'])->select();

    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/1/5 14:40
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 主次干道
     */
    public function getProjectSelectLists(){

        $single = $this->request->param('single',0);

        $community_id = $this->request->param('community_id');

        $res = CommunityProjectPivot::with(['project'=>function($query)use($single){
            if (intval($single) === 1){
                $query->with(['target'])->where(['single'=>0]);
            }else if (intval($single) === 2){
                $query->with(['target'])->where(['single'=>1]);
            }else{
                $query->with(['target']);
            }
            return $query;
            //->where(['community_id'=>$community_id])
        }])->select()->filter(function (CommunityProjectPivot $communityProjectPivot){
            if (!is_null($communityProjectPivot->project)){
                return true;
            }
        });
        $new_arr =[];
        foreach ($res as $key=>$v){
            $new_arr[$key]['value'] = $v['project']['id'];
            $new_arr[$key]['label'] = $v['project']['project_title'];
        }
        $aaa_arr[] = reset($new_arr);
        return $this->response($aaa_arr);
//        $res = Project::field('id,project_title as label')->with(['target'])->select();

    }



    /**
     * Created by PhpStorm.
     * User: 刘海龙
     * Date: 2022/1/1
     * Time: 12:05
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *   //获取中间件表的项目ids
     */
    public function showProjectIds(){
        $community_id = $this->request->param('community_id');
        $res = CommunityProjectPivot::field('project_id')->where(['community_id'=>$community_id])->select();
        $new_arr = [];
        foreach ($res as $key=>$v){
            $new_arr[] = $v['project_id'];
        }
        if(empty($new_arr)){
            return $this->response(403,'暂无数据');
        }else{
            return $this->response($new_arr);
        }
    }

    /**
     * Created by PhpStorm.
     * User: 刘海龙
     * Date: 2022/1/2
     * Time: 11:58
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 根据项目id 获取项目指标
     */
    public function getProjectTargetList(){
        $project_ids = $this->request->param('project_id');

        if (is_array($project_ids)){
            $project_id = $project_ids[0];
        }else{
            $project_id = $project_ids;
        }
        $res = ProjectTarget::field('id as value,target_title as label,attribute_id')->with(['attribute'])->where(['project_id'=>$project_id])->select()->each(function ($item,$key){
            if(!empty($item['attribute'])){
                $item['label'] = '['.$item['attribute']['title'].']'.$item['label'];
                return $item;
            }
        });
        return $this->response($res);
    }

    /**
     * Created by PhpStorm.
     * User: 刘海龙
     * Date: 2022/1/1
     * Time: 12:07
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 关联社区项目
     */
    public function saveCommunityAndProject(){
        $data = $this->request->param();

        $res = CommunityProjectPivot::where(['community_id'=>$data['community_id']])->select();
        if(!$res->isEmpty()){
            $res->delete();
        }
        foreach ($data['project'] as $key=>$v){
            CommunityProjectPivot::create([
                'community_id'=>$data['community_id'],
                'project_id'=>$v
            ]);
        }
        $content = [
            'community_id'=>$data['community_id'],
            'project_id'=>json_encode($data['project'])
        ];
        AdminLog::record('社区关联项目', $content, $this->request->uid, $this->request->username);
        return $this->response();
    }
    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2021/12/29 10:26
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 保存项目
     */
    public function saveProject(){
        $id = $this->request->param('id', 0);
        $data = $this->request->param();
        $data['uid'] = $this->request->uid; //用户id
        if (intval($id) === 0) {
            Project::create($data);
        } else {
            $res = Project::find($id);
            if (is_null($res)) {
                return $this->response(403, '数据不存在');
            }
            $res->save($data);
        }
        AdminLog::record(intval($id) === 0 ? '新增项目' : '编辑项目', $this->request->param(), $this->request->uid, $this->request->username);
        return $this->response();
    }
    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2021/12/29 10:44
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 保存项目指标
     */
    public function saveProjectTarget(){
        $id = $this->request->param('id', 0);
        $data = $this->request->param();
        $data['uid'] = $this->request->uid; //用户id
        if (intval($id) === 0) {
            ProjectTarget::create($data);
        } else {
            $res = ProjectTarget::find($id);
            if (is_null($res)) {
                return $this->response(403, '数据不存在');
            }
            $res->save($data);
        }
        AdminLog::record(intval($id) === 0 ? '新增项目指标' : '编辑项目指标', $this->request->param(), $this->request->uid, $this->request->username);
        return $this->response();
    }
    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2021/12/29 10:30
     * @param $id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 删除项目及指标
     */
    public function deleteProject($id)
    {
        $res = Project::with(['target'])->find($id);
        if (is_null($res)) {
            return $this->response(403, '找不到该资源信息');
        }
        //->force()
        $res->together(['target'])->delete();
        AdminLog::record('删除项目及指标', $this->request->param(), $this->request->uid, $this->request->username);
        return $this->response();
    }
    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2021/12/29 10:51
     * @param $id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 删除指标
     */
    public function deleteTarget($id)
    {
        $res = ProjectTarget::find($id);
        if (is_null($res)) {
            return $this->response(403, '找不到该资源信息');
        }
        //->force()
        $res->delete();
        AdminLog::record('删除指标', $this->request->param(), $this->request->uid, $this->request->username);
        return $this->response();
    }
    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2021/12/29 9:23
     * @return \think\response\Json
     * 导入模板
     */
    public function importExcel(){
        if (!$this->request->file('file')) {
            return $this->response(501, '请选择上传文件');
        }
        $file = $this->request->file('file');
        $result = $this->saveImportExcel($file, 'import_excel');
        $is_bool = Project::saveImportExcel($result,$this->request->uid);
        if ($is_bool === 200) {
            //日志
            AdminLog::record('导入模版', $this->request->param(), $this->request->uid, $this->request->username);
            return $this->response();
        } else {
            return $this->response(403, '导入问卷失败');
        }
    }


    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/1/5 11:30
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 数据列表
     */
    public function attributeList(){
        $limit = $this->request->param('limit',10);
        $res = Attribute::paginate($limit);
        return $this->response($res);
    }


    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/1/5 11:27
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 保存职能属性
     */
    public function attributeSave(){
        $id = $this->request->param('id', 0);
        $data = $this->request->param();
        if (intval($id) === 0) {
            Attribute::create($data);
        } else {
            $attribute = Attribute::find($id);
            $attribute->save($data);
        }
        AdminLog::record(intval($id) === 0 ? '新增职能属性' : '编辑职能属性', $this->request->param(), $this->request->uid, $this->request->username);
        return $this->response();
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/1/5 11:37
     * @param $id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 删除职能属性
     */
    public function deleteAttribute($id){
        $res = Attribute::find($id);
        if (is_null($res)) {
            return $this->response(403, '找不到该资源信息');
        }
        //->force()
        $res->delete();
        AdminLog::record('删除职能属性', $this->request->param(), $this->request->uid, $this->request->username);
        return $this->response();
    }
}
